package com.iretailer.util;

import com.iretailer.quartz.alarmMail.MaillMessage;
import com.sun.mail.util.MailSSLSocketFactory;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.*;
import javax.mail.util.ByteArrayDataSource;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.security.Security;
import java.util.List;
import java.util.Properties;


public class JavaMailWithAttachment {
	
	
	private MimeMessage message;
	private Session session;
	private Transport transport;
	private String mailHost = "";
	private String sender_username = "";
	private String sender_password = "";
	
	private Properties properties = new Properties();
	/**
	 * 初始化方法
	 */
     public JavaMailWithAttachment(boolean debug, MaillMessage mm){

//    	 InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("mail.properties");
    	 
    	 //设置SSL连接、邮件环境
       Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
       properties.put("mail.host",mm.getMailHost());
       properties.put("mail.username", mm.getUsername());
       if(mm.getPassword()!=null&&mm.getPassword().trim().length()>0){


           properties.setProperty("mail.transport.protocol", "smtps");
    	   properties.put("mail.password", mm.getPassword());
    	   properties.put("mail.smtp.socketFactory.class", mm.getSocketClass());
    	   properties.put("mail.smtp.socketFactory.fallback", mm.getSocketFallback());

    	   //ssl 证书 企业邮箱
           MailSSLSocketFactory sf = null;
           try {
               sf = new MailSSLSocketFactory();
               sf.setTrustAllHosts(true);
           } catch (GeneralSecurityException e1) {
               e1.printStackTrace();
           }
           properties.put("mail.smtp.ssl.enable", "true");
           properties.put("mail.smtp.ssl.socketFactory", sf);

       }
       properties.put("mail.smtp.port", mm.getSmtpPort());


       
//          final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
//    	    properties.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY); 
//    	    properties.setProperty("mail.smtp.socketFactory.fallback", "false");
//			properties.load(in);
		
		this.mailHost = properties.getProperty("mail.host");
		
		this.sender_username = properties.getProperty("mail.username");
		
		this.sender_password = properties.getProperty("mail.password");
		
		
    	 session = Session.getInstance(properties);
    	 session.setDebug(debug);
    	 message = new MimeMessage(session);
    	 
     }
     
     public boolean doSendEmail(String subject, String sendContent, List<String> receiveUsers, List<byte[]> images, List<String> cids ) throws MessagingException{
    	 boolean result = false;
		
			//发件人
			InternetAddress from = new InternetAddress(sender_username);
			message.setFrom(from);
			
			//收件人
			InternetAddress[] tos = new InternetAddress[receiveUsers.size()];
			for (int i = 0; i < receiveUsers.size(); i++) {
				tos[i] = new InternetAddress(receiveUsers.get(i));
			}
			message.setRecipients(Message.RecipientType.TO, tos);
			
			//邮件主题
			message.setSubject(subject);
			
			//向 multipart 对象中添加邮件的各个部分内容，包括文本内容和附件
			Multipart multipart = new MimeMultipart();
			
			//添加邮件正文
			BodyPart contentPart = new MimeBodyPart();
			contentPart.setContent(sendContent,"text/html;charset=UTF-8");
			multipart.addBodyPart(contentPart);
			//内嵌图片部分
			if( images !=null && images.size() >0){
				for (int i = 0; i < images.size(); i++) {
					MimeBodyPart imagePart = new MimeBodyPart();
					
//					DataSource source = new FileDataSource(images.get(i));
					DataSource source = new ByteArrayDataSource(images.get(i), "application/png");
					imagePart.setDataHandler(new DataHandler(source));
					imagePart.setContentID(cids.get(i));   //cid的值  
					multipart.addBodyPart(imagePart);  

					
				}

				
			}
			
			//将 multipart 对象放到 message中
			message.setContent(multipart);
			//保存邮件
			message.saveChanges();
			
			Transport.send(message);
			
			result = true;
    	 
		return result;
     }
/**
 * 发送邮件
 * @param subject 主题
 * @param sendContent 内容
 * @param receiveUsers 收件人
 * @param images 内嵌图片
 * @param attachments 附件
 * @throws MessagingException 
 * @throws UnsupportedEncodingException
 */
     
     public boolean doSendEmail(String subject, String sendContent, List<String> receiveUsers, List<byte[]> images, List<String> cids, List<File> attachments) throws MessagingException, UnsupportedEncodingException {
    	 boolean result = false;
    	 try {
    		 //发件人
			InternetAddress from = new InternetAddress(sender_username);
			message.setFrom(from);
			
			//收件人
//			InternetAddress to = new InternetAddress(receiveUser);
			InternetAddress[] tos = new InternetAddress[receiveUsers.size()];
			for (int i = 0; i < receiveUsers.size(); i++) {
				tos[i] = new InternetAddress(receiveUsers.get(i));
			}
			message.setRecipients(Message.RecipientType.TO, tos);
			
			//邮件主题
			message.setSubject(subject);
			
			//向 multipart 对象中添加邮件的各个部分内容，包括文本内容和附件
			Multipart multipart = new MimeMultipart();
			
			//添加邮件正文
			BodyPart contentPart = new MimeBodyPart();
			contentPart.setContent(sendContent,"text/html;charset=UTF-8");
			multipart.addBodyPart(contentPart);
			//内嵌图片部分
			if( images !=null && images.size() >0){
				for (int i = 0; i < images.size(); i++) {
					MimeBodyPart imagePart = new MimeBodyPart();
					
//					DataSource source = new FileDataSource(images.get(i));
					DataSource source = new ByteArrayDataSource(images.get(i), "application/png");
					imagePart.setDataHandler(new DataHandler(source));
					imagePart.setContentID(cids.get(i));   //cid的值  
					multipart.addBodyPart(imagePart);  

					
				}

				
			}
			
			
			//添加附件内容
			if(attachments !=null &&attachments.size() > 0){
				for (int i = 0; i < attachments.size(); i++) {
					BodyPart attachmentBodayPart = new MimeBodyPart();
					DataSource source = new FileDataSource(attachments.get(i));
					attachmentBodayPart.setDataHandler(new DataHandler(source));
					//MimeUtility.encodeWord 可以避免文件乱码
					attachmentBodayPart.setFileName(MimeUtility.encodeWord(attachments.get(i).getName()));
					multipart.addBodyPart(attachmentBodayPart);
				}
				
			}
			//将 multipart 对象放到 message中
			message.setContent(multipart);
			//保存邮件
			message.saveChanges();
			
			transport = session.getTransport("smtp");
			//smtp验证 ，
			transport.connect(mailHost, sender_username,sender_password);
			//发送
			transport.sendMessage(message, message.getAllRecipients());
			
			result = true;
		}finally{
			if(transport !=null){
				try {
					transport.close();
					
				} catch (MessagingException e) {
					e.printStackTrace();
				}
			}
		}
    	 return result;
    	 
    	 
     }
}
